import { submitAVote, submitTheVerification } from "@/api/partyBuilding";
import { useTemplateEditing } from "@/store/modules/templateEditing";
import { tipsMessage } from "@/utils/messageConfig.js";
import { debounce, flatten, compact } from "lodash";
import { useRoute } from "vue-router";
import { toRaw } from "vue";
import {
  DELAY_TIME,
  STAFFING,
  DELAY_THE_SHUTDOWN_TIME,
  SUBMIT_DATA_COLLATION,
  BEAUTIFUL_MOBILE_NAME,
  SUCCESS_MESSAGE,
  ERROR_MESSAGE,
  MODULE_TYPE,
} from "@/utils/mockConfiguration/mockConfig";

const { VALIDATION_MODULE } = MODULE_TYPE;
const { SUCCESS_CONFIGURE_VERIFICATION } = SUCCESS_MESSAGE;
const { ERROR_VERIFICATION_FAILED, ERROR_ASSOCIATION_OPTION_EMPTY, ERROR_OPTION_EMPTY, ERROR_DESCRIPTION__EMPTY } = ERROR_MESSAGE;
const templateEditing = useTemplateEditing();
/**
 * 模板设置
 * @param {Object} currentSettings - 当前模板的设置数据
 * @param {number} templatePageIndex - 当前选中的模板页索引
 * @param {Array} selectedModules - 选中的模块id列表
 */
const { currentSettings, templatePageIndex, selectedModules } = storeToRefs(templateEditing);
// 默认提示模板
const defaultModule = falsyVars => `<div>${falsyVars}</div>`;
export default function useSubmitTheVerification() {
  const id = ref(""); //当前模板id
  const mxSsoToken = ref(""); //moa的认证token
  onMounted(() => {
    const route = useRoute();
    const { id: Id, mx_sso_token } = route.query;
    id.value = Id;
    mxSsoToken.value = mx_sso_token ?? "";
  });
  /**
   * 校验没主选项或者有了主选项且有键名校验通过，当有选项没填写，则校验失败
   * @param options 选项数据
   */
  const isOptionsValid = options => {
    return !options || !options.some(list => list.id === "");
  };
  /**
   * 校验关联规则，当有选项没填写，则校验失败
   * @param {Object} value 当前模块数据
   */
  const correlationRules = value => value.every(item => item.questionId && item.optionIds.length);
  /**
   * 简答题和选择题模块校验
   * @param {Object} value 当前模块数据
   */
  const checkOptionProperties = value => {
    const {
      businessData,
      cssStyle: { i },
    } = value;
    const { desc, assocRules, id, options } = businessData;
    const falsyVars = []; // 未填写的选项
    //检查题目描述是否为空
    !desc && falsyVars.push(ERROR_DESCRIPTION__EMPTY);
    //检查选项是否有键名为空，有则提示
    isOptionsValid(options) || falsyVars.push(ERROR_OPTION_EMPTY);
    //如果有关联规则检查关联规则数据是否为空，有则提示
    correlationRules(assocRules) || falsyVars.push(ERROR_ASSOCIATION_OPTION_EMPTY);
    if (!falsyVars.length) {
      return "";
    }
    falsyVars.unshift(`第【${id}】题`);
    // 收集校验不通过的模块
    selectedModules.value.push(i);
    return falsyVars.join("，");
  };
  /**
   * 投票模块校验
   * @param {Object} value 当前模块数据
   */
  const checkUserProperties = value => {
    const {
      businessData,
      cssStyle: { i },
    } = value;
    const falsyVars = Object.keys(STAFFING)
      .filter(varName => !businessData[varName])
      .map(item => `${STAFFING[item]}、`);
    if (!falsyVars.length) {
      return "";
    }
    // 收集校验不通过的模块
    selectedModules.value.push(i);
    return `${falsyVars.join("")}：内容为空`;
  };
  /**
   * 模块校验
   * @param {Object} item 当前模块数据
   */
  const moduleValidation = item =>
    item.moduleId === BEAUTIFUL_MOBILE_NAME ? checkUserProperties(item) : checkOptionProperties(item);
  /**
   * 校验
   */
  const calibration = () => {
    const { modules } = currentSettings.value;
    // 需要检验的模块
    const presetModules = toRaw(modules).filter(item => VALIDATION_MODULE.includes(item.moduleId));
    selectedModules.value = []; //重置选中模块
    templatePageIndex.value = null; //重置选中模块
    const completeLearning = [];
    presetModules.forEach(item => {
      const data = moduleValidation(item);
      data && completeLearning.push(data);
    });
    if (!completeLearning.length) {
      tipsMessage({ type: "success", message: SUCCESS_CONFIGURE_VERIFICATION });
      return true;
    }
    //提示校验不通过内容
    tipsMessage({ type: "error", message: ERROR_VERIFICATION_FAILED });
    completeLearning.forEach(falsyVars => tipsMessage({ type: "warning", message: defaultModule(falsyVars) }));
    return false;
  };
  /**
   * 查找当前选项的输入原因
   * @param {Array} data  选项数据
   * @param {String} id  当前选项id
   */
  const findTheCause = (data, id) => data.find(item => item.id === id)?.input ?? ""; //需要在数组中查找对应id的选项的填写原因数据。
  const loading = ref(false);
  /**
   * 单项数据合并处理
   * @param object 要合并的对象数据
   */
  const createObject = object => ({ ...SUBMIT_DATA_COLLATION, ...object });
  /**
   * 数组数据合并处理
   * @param id 选项id
   * @param needFeedback 是否有答题反馈
   * @param selectValue 选择的选项
   * @param feedback 答题反馈内容
   * @param options 选项数据
   */
  const multipleItemsCreateObject = ({ id, needFeedback, selectValue, feedback, options }) => {
    return selectValue?.map(itemValue =>
      createObject({
        objectId: id,
        replyId: itemValue,
        replyRemark: findTheCause(options, itemValue),
        replyContent: needFeedback ? feedback : "",
      }),
    );
  };
  /**
   * 投票数据处理
   */
  const votingDataProcessing = item => {
    const { userCode } = item.businessData;
    return item.vote && createObject({ objectId: userCode, replyId: userCode });
  };
  /**
   * 简答数据处理
   */
  const shortAnswerDataProcessing = item => {
    const { content, id } = item.businessData;
    return createObject({ objectId: id, replyContent: content ?? "" });
  };
  /**
   * 选择题数据处理
   */
  const multipleChoiceDataProcessing = item => {
    const { id, selectType, needFeedback, selectValue, feedback, options } = item.businessData;
    return selectType === "radio"
      ? createObject({
          objectId: id,
          replyId: selectValue ?? "",
          replyRemark: findTheCause(options, selectValue),
          replyContent: needFeedback ? feedback : "",
        })
      : multipleItemsCreateObject(item.businessData);
  };
  /**
   * 提交数据配置函数
   */
  const dataProcessingConfig = {
    beautifulMobilePerson: votingDataProcessing,
    shortAnswerQuestion: shortAnswerDataProcessing,
    choiceQuestion: multipleChoiceDataProcessing,
  };
  /**
   * 提交数据整理
   */
  const submitData = () => {
    const { modules } = currentSettings.value;
    //预设模块类型
    const presetModules = toRaw(modules).filter(item => VALIDATION_MODULE.includes(item.moduleId));
    /**
     * 提交数据整理,过滤掉值为空的数据
     */
    const newData = compact(
      flatten(
        presetModules.map(item => {
          const handler = dataProcessingConfig[item.moduleId];
          return handler?.(item);
        }),
      ),
    ).filter(({ replyId, replyRemark, replyContent }) => replyId || replyRemark || replyContent);
    return {
      id: id.value,
      data: JSON.stringify(newData),
      mxSsoToken: mxSsoToken.value,
    };
  };
  /**
   * 提交规则校验
   */
  const lodCheckSubmit = async () => {
    if (!calibration()) {
      //当完整性校验不通过，弹出提示
      return;
    }
    const { msg } = await submitTheVerification(submitData());
    tipsMessage({ type: "success", message: msg });
  };
  const checkSubmit = debounce(lodCheckSubmit, DELAY_TIME);
  /**
   * 提交投票
   */
  const submit = async () => {
    try {
      loading.value = true;
      const calibration = await submitAVote(submitData()); //提交投票数据
      tipsMessage({ type: "success", message: calibration.msg });
      setTimeout(() => window.close(), DELAY_THE_SHUTDOWN_TIME);
    } catch (error) {
      //框架统一对catch里面已做处理 这里无需重复错误提示。
    } finally {
      loading.value = false;
    }
  };
  return {
    checkSubmit, //提交规则校验
    submit, //提交
    loading, //提交loading
    calibration, //完整性校验
    submitData, //已答数据
  };
}
